/* 地图信息 */
var defaultPointIcon = "/wcsi/img/defaultShop.png";
var arcGisUrl = "http://39.107.125.44:6080";
var map;
var toolbar;
var partLayer;
var centerX = 106.638;
var centerY = 26.684;
var shopPoint;
var drawHandler;
var oldPoint;
require([ "esri/map", "esri/Color", "esri/graphic", "esri/InfoTemplate",
		"esri/SpatialReference", "esri/renderers/HeatmapRenderer",
		// 控件
		"esri/dijit/OverviewMap", "esri/dijit/Scalebar",
		"esri/dijit/Measurement", "esri/units",
		// 图层
		"tdlib/TDTLayer", "tdlib/TDTAnnoLayer", "tdlib/TDT_ImgLayer",
		"tdlib/TDT_ImgAnnoLayer", "esri/layers/GraphicsLayer",
		"esri/layers/ArcGISDynamicMapServiceLayer",
		"esri/layers/ArcGISTiledMapServiceLayer", "esri/layers/FeatureLayer",
		// 图形要素
		"esri/geometry/Point", "esri/geometry/Polyline",
		"esri/geometry/Polygon", "esri/geometry/Circle",
		// 样式
		"esri/symbols/TextSymbol", "esri/symbols/SimpleMarkerSymbol",
		"esri/symbols/PictureMarkerSymbol", "esri/symbols/SimpleLineSymbol",
		"esri/symbols/SimpleFillSymbol",
		// 标签
		"esri/symbols/Font", "esri/layers/LabelClass",
		// 查询
		"esri/tasks/query", "esri/tasks/QueryTask", "esri/toolbars/draw",
		"esri/dijit/Popup", "esri/dijit/PopupTemplate", "dojo/dom",
		"dojo/dom-construct" ], function(Map, Color, Graphic, InfoTemplate,
		SpatialReference, HeatmapRenderer, OverviewMap, Scalebar, Measurement,
		Units, TDTLayer, TDTAnnoLayer, TDT_ImgLayer, TDT_ImgAnnoLayer,
		GraphicsLayer, ArcGISDynamicMapServiceLayer,
		ArcGISTiledMapServiceLayer, FeatureLayer, Point, Polyline, Polygon,
		Circle, TextSymbol, SimpleMarkerSymbol, PictureMarkerSymbol,
		SimpleLineSymbol, SimpleFillSymbol, Font, LabelClass, Query, QueryTask,
		Draw, Popup, PopupTemplate, dom, domConstruct) {

	map = new Map("map", {
		slider : false,
		logo : false,
		showLabels : true,
		center : [ centerX, centerY ],
		zoom : 14,
		minZoom : 17,
	});

	// 初始化比例尺
	var scalebar = new Scalebar({
		map : map,
		attachTo : "bottom-left",
		scalebarUnit : "dual",
	});

	// 显示比例尺
	scalebar.show();
	drawHandler = Draw;
	var vec = new TDTLayer();// 切片线画图
	var veca = new TDTAnnoLayer();// 切片标注
	var img = new TDT_ImgLayer();
	var imga = new TDT_ImgAnnoLayer();
	map.addLayer(vec);
	map.addLayer(veca);

	map.graphics.on("mouse-down", function(evt) {
		console.log("graphicslayer:mouse-down");
		if (evt.graphic) {
			shopPoint = evt.graphic;
		}
		if (shopPoint) {
			oldPoint = evt.mapPoint;
			shopPoint.isMouseDown = true;
			map.disableMapNavigation();
			map.disablePan();
		}
	});
	map.on("mouse-drag", function(evt) {
		console.log("map:mouse-drag");
		if (shopPoint) {
			if (shopPoint.isMouseDown) {
				shopPoint.setGeometry(evt.mapPoint);
			}
		}
	});
	
	map.on("mouse-up", function(evt) {
		console.log("map:mouse-up");
		if (shopPoint) {
			oldPoint = null;
			map.enableMapNavigation();
			map.enablePan();
			shopPoint.isMouseDown = false;
		}
	});
	
//	//鼠标经过
//	map.graphics.on("mouse-over", function(evt) {
//		console.log("graphicslayer:mouse-over");
//		setPolygonMouseInSymbol(evt.graphic);
//		//evt.graphic.setSymbol(symbol);
//	});
//
//	//鼠标移开
//	map.graphics.on("mouse-out", function(evt) {
//		console.log("graphicslayer:mouse-out");
//		setPolygonMouseOutSymbol(evt.graphic);
//		//evt.graphic.setSymbol(symbol);
//	});
	
});

//创建坐标点
function createPoint(data){
	var symbol = new esri.symbol.PictureMarkerSymbol(defaultPointIcon,20,20).setOffset(0,10);
	var longitude =  data.longitude == '0' ? centerX : data.longitude;
	var latitude = data.latitude == '0' ? centerY : data.latitude;
	var myPoint = {
        "geometry": {
        	"type":"point",
            "x": longitude,
            "y": latitude,
            "spatialReference": { "wkid": 4326 }
        },
        "attributes": data,
        "symbol": symbol,
        "showType":"shop"
    };
	
	var graphic = getcurrentGraphic("shop");
	
	if (graphic == null) {
		graphic = new esri.Graphic(myPoint);
		graphic.symbol = symbol;
		graphic.showType = "shop";
	} else {
		var geometry = graphic.geometry;
		geometry.x = longitude;
		geometry.y = latitude;
		graphic.showType = "shop";
		graphic.setGeometry(geometry);
		graphic.setSymbol(symbol);
	}
	map.graphics.add(graphic);
	setTimeout(function() {
		map.centerAndZoom(graphic.geometry,map.getLevel());
//		map.centerAt(graphic.geometry);
	},500);
	
	shopPoint = graphic;
	return graphic;
}

function getcurrentGraphic(type) {
	var graphics;
	graphics = map.graphics.graphics;
	for (var i = 0; i < graphics.length; i++) {
		if (graphics[i]) {
			if (graphics[i].showType && graphics[i].showType == type) {
				return graphics[i];
			}
		}
	}
	return null;
};


(function () {
	
    //查询
    jQuery('.app-btn-search').on('click',function(){
        serverData.key=jQuery("#search").val();
        serverTable.draw();
    });
    //撤销查询
    jQuery('.app-btn-cancel').on('click',function(){
        jQuery('#search').val('');
        serverData.key='';
        serverTable.draw();
    });
    
    ///认证通过
    jQuery('.accessBtn').on('click', function () {
    	if (jQuery("#checkEditForm") && !jQuery("#checkEditForm").Validform({
			tiptype : 3,
			showAllError : true
		}).check(false)) {
			return;
		};
		    var id = jQuery('#id').val();
	        var url = window.rootPath + "/ui/BusinesssellerAuthentication/accessCheck";
	        var d;
	        if(id!=''){
	        		d = {
					"id": id,
					"memo": jQuery('#memo').val(),
					"longitude":shopPoint.geometry.x,
	    				"latitude":shopPoint.geometry.y,
     	        };
		        jQuery.ajax({
		            type: 'post',
		            url: encodeURI(url),
		            data: JSON.stringify(d),
		            dataType: 'json',
		            contentType: 'application/json;charset=utf-8',
		            success: function (data) {
		            	if(data.code==-1){
		            		message("认证失败！");
		            	}
		            	else{
		            		message("认证通过！")
		            	}
		            	jQuery('#checkModal').modal('hide');
		                serverTable.draw(false);
		            }
		        });
	        }
    });
    
  ///认证拒绝
    jQuery('.rejectBtn').on('click', function () {
    	if (jQuery("#checkEditForm") && !jQuery("#checkEditForm").Validform({
			tiptype : 3,
			showAllError : true
		}).check(false)) {
			return;
		};
		    var id = jQuery('#id').val();
	        var url = window.rootPath + "/ui/BusinesssellerAuthentication/rejectCheck";
	        var d;
	        if(id!=''){
	        		d = {
					"id": id,
					"memo": jQuery('#memo').val(),
					"longitude":shopPoint.geometry.x,
					"latitude":shopPoint.geometry.y,
     	        };
		        jQuery.ajax({
		            type: 'post',
		            url: encodeURI(url),
		            data: JSON.stringify(d),
		            dataType: 'json',
		            contentType: 'application/json;charset=utf-8',
		            success: function (data) {
		            	if(data.code==-1){
		            		message("拒绝失败！");
		            	}
		            	else{
		            		message("拒绝通过！")
		            	}
		            	jQuery('#checkModal').modal('hide');
		                serverTable.draw(false);
		            }
		        });
	        }
    });

    var serverData = {};
    var serverTable;
    jQuery(document).ready(function () {
        serverTable = jQuery('#dataTable').DataTable({
            "serverSide": true,
            "ordering": false,
            "ajax": {
                "dataType": "json",
                "type": "get",
                "cache": false,
                "url":window.rootPath+ '/ui/BusinesssellerAuthentication/getauthenticationpage',
                "data": function (d) {
                    return $.extend({}, d, serverData);
                }
            },
            columns: [
                {
                data: null
                },
                {
                    data: null,
                    defaultContent: "",
                    render: function (data, type, full, meta) {
                    	var accessed='disabled="true"';
                    	var rejected='disabled="true"';
                    	
                    	if(data.infoState.title=='待认证'){
                    		accessed= '';
                    		rejected='';
                    	}
                        var operate ='<button type="button" class="btn btn-sm btn-info accessBtn1" title="通过" '+accessed+'><i class="fa fa-pencil"></i></button>'
                            +'<button type="button" class="btn btn-sm btn-info rejectBtn1" title="拒绝" '+rejected+'><i class="fa fa-remove"></i></button>'
                            +'<button type="button" class="btn btn-sm btn-info searchBtn" title="查看"><i class="fa fa-search"></i></button>';
                        return operate;

                    }
                },
                {
                    //data: 'infoState.title'
                	data: null,
            	    render : function(data,type, full,meta) {
						var dOut;
						if(data.infoState!=undefined){
						/*if (data.infoState.title == '待认证') {
							dOut = '<td class="center" ><span class="badge label-pill label-primary">待认证</span></td>';
						} else if (data.infoState.title == '认证拒绝') {
							dOut = '<td class="center" ><span class="badge label-pill label-danger">认证拒绝</span></td>';
						} else if (data.infoState.title == '认证通过') {
							dOut = '<td class="center" ><span class="badge label-pill label-success">认证通过</span></td>';
						} else if (data.infoState.title == '初始化') {
							dOut = '<td class="center" ><span class="badge label-pill label-default">初始化</span></td>';
						} else if(data.infoState.title	==null){
							dOut='';
						}*/
							if (data.infoState.title == '待认证') {
								dOut = '<td class="center" ><img width="100%" src="../img/authentication_in.png"/></td>';
							} else if (data.infoState.title == '认证拒绝') {
								dOut = '<td class="center" ><img width="100%" src="../img/authentication_notaccess.png"/></td>';
							} else if (data.infoState.title == '认证通过') {
								dOut = '<td class="center" ><img width="100%" src="../img/authentication_access.png"/></td>';
							} else if (data.infoState.title == '初始化') {
								dOut = '<td class="center" ><img width="100%" src="../img/authentication_init.png"/></td>';
							} else if(data.infoState.title	==null){
								dOut='';
							}
						}
						return dOut;
					}
                },
                {
                    data: 'shopName',
                    render:function(data,type,full,meta){
	                	if(data == null || data == undefined || data == ""){
							return data;
						}else{
							return (data.length > 30) ? '<font title="'+data+'">'+data.substring(0,30)+'...'+'</font>' : data;
						}
					}
                },
                {
                    data: 'shopAdress',
                    render:function(data,type,full,meta){
	                	if(data == null || data == undefined || data == ""){
							return data;
						}else{
							return (data.length > 30) ? '<font title="'+data+'">'+data.substring(0,30)+'...'+'</font>' : data;
						}
					}
                },
                {
                    data: 'businesssellerBaseInfo.bussinessLevel.levelName',
                    render:function(data,type,full,meta){
	                	if(data == null || data == undefined || data == ""){
							return data;
						}else{
							return (data.length > 30) ? '<font title="'+data+'">'+data.substring(0,30)+'...'+'</font>' : data;
						}
					}
                },
                {
                    data: 'businesssellerBaseInfo.bussinessLevel.phoneNumber',
                    render:function(data,type,full,meta){
	                	if(data == null || data == undefined || data == ""){
							return data;
						}else{
							return (data.length > 30) ? '<font title="'+data+'">'+data.substring(0,30)+'...'+'</font>' : data;
						}
					}
                },
                {
                    data: 'businesssellerBaseInfo.bussinessLevel.manager.name',
                    render:function(data,type,full,meta){
	                	if(data == null || data == undefined || data == ""){
							return data;
						}else{
							return (data.length > 30) ? '<font title="'+data+'">'+data.substring(0,30)+'...'+'</font>' : data;
						}
					}
                },
                {
                    data: 'areaMeasure',
                    render:function(data,type,full,meta){
	                	if(data == null || data == undefined || data == ""){
							return data;
						}else{
							return (data.length > 30) ? '<font title="'+data+'">'+data.substring(0,30)+'...'+'</font>' : data;
						}
					}
                },
                {
                    data: 'signPerson'
                },
                {
                    data: 'managementRange',
                    render:function(data,type,full,meta){
	                	if(data == null || data == undefined || data == ""){
							return data;
						}else{
							return (data.length > 30) ? '<font title="'+data+'">'+data.substring(0,30)+'...'+'</font>' : data;
						}
					}
                },
                {
                    data: 'submitDate',
                    render: function (data, type, full, meta) {
                        if (data)
                            return moment(data).format('YYYY/MM/DD');
                        else
                            return '';
                    }
                },
                {
                    data: 'checkDate',
                    render: function (data, type, full, meta) {
                        if (data)
                            return moment(data).format('YYYY/MM/DD');
                        else
                            return '';
                    }
                },
                {
                    data: 'managementPerson.name'
                }
              ],
            "drawCallback": function (oSettings) {
                var k = 0;
                var total = oSettings.aiDisplay.length + oSettings._iDisplayStart;

                for (var i = oSettings._iDisplayStart, iLen = total; i < iLen; i++) {
                    $('td:eq(0)', oSettings.aoData[oSettings.aiDisplay[k]].nTr).text(i + 1);
                    k++;
                }

                serverTable.off('click', 'tr');
                serverTable.on('click', 'tr', function (event) {
                    event = event || window.event;
                    var target = event.target || event.scrElement;
                    var data = serverTable.row(this).data();
                    if (target.className.indexOf('fa-remove') != -1 || target.className.indexOf('rejectBtn1') != -1) {
                        rejectCheckQ(data);
                    }
                    if (target.className.indexOf('fa-pencil') != -1 || target.className.indexOf('accessBtn1') != -1) {
                    	accessCheckQ(data);
                    }
                    
                    if (target.className.indexOf('fa-search') != -1 || target.className.indexOf('searchBtn') != -1) {
                        showDetail(data);
                    }

                    return;
                });
            }
        });
        var deleteAccount = function (data) {
            if (!data) return;
            $.springLemonDialog({
                content: '确认账号：' + data.accountName + '？',//确认文本
                clickButton: function (sender, modal, index) {//按钮事件处理
                    //index:0 确认    1：取消
                    //sender:事件源 如按钮，sender.html()可得到按钮文字如：取消
                    if (index == 0) {
                        var url =window.rootPath+ "/api/accounts/" + data.id;
                        jQuery.ajax({
                            url: encodeURI(url),
                            cache: false,
                            type: "delete",
                            dataType: "json",
                            success: function (data) {
                                serverTable.draw(false);
                            }
                        });
                    }
                    $(this).closeDialog(modal);
                }

            });
        };
        var rejectCheckQ=function(data){
	        var url = window.rootPath + "/ui/BusinesssellerAuthentication/rejectCheck";
	        var d;
	        	  d = {
	        			"id": data.id,
	     	            "memo": jQuery('#memo').val()
	     	        };
	        jQuery.ajax({
	            type: 'post',
	            url: encodeURI(url),
	            data: JSON.stringify(d),
	            dataType: 'json',
	            contentType: 'application/json;charset=utf-8',
	            success: function (data) {
	            	if(data.code==-1){
	            		message("拒绝失败！");
	            	}
	            	else{
	            		message("拒绝通过！")
	            	}
	                serverTable.draw(false);
	            }
	        });
        };
        
        var accessCheckQ=function(data){
	        var url = window.rootPath + "/ui/BusinesssellerAuthentication/accessCheck";
	        var d;
	        	  d = {
	        			"id": data.id,
	     	            "memo": "快速认证"
	     	        };
	        jQuery.ajax({
	            type: 'post',
	            url: encodeURI(url),
	            data: JSON.stringify(d),
	            dataType: 'json',
	            contentType: 'application/json;charset=utf-8',
	            success: function (data) {
	            	if(data.code==-1){
	            		message("认证失败！");
	            	}
	            	else{
	            		message("认证通过！")
	            	}
	                serverTable.draw(false);
	            }
	        });
        };
        $("#avatar").error(function() { 
        	$(this).attr("src", "../img/empty.png"); 
        	$(this).error=null;
        	}); 
        
        /*jQuery("#avatar").bind("click",function(){
    		PictureUpload();
    	});*/
    	/**
    	 * 图片上传
    	*/
    	PictureUpload = function()
    	{
    	     var root=window.rootPath;	   
    	     WebFilesUploader(
    		           {
    			        _webuploader:{
    			            server: root + '/a/'+jQuery('#id').val()+'/avatar',
    			        	chunked:false
    			        }
    			    },
    			    function(jsons)
    			    {
    			    	var avatarUrl=window.rootPath+'/a/'+'avatar/'+jQuery('#id').val();
    			    	/*jQuery("#avatar").prop("src","#");*/
    					jQuery("#avatar").prop("src",avatarUrl+'?t='+Math.random());
    			    });
    	};
    	
        var showDetail=function(data){
        	if(!data) return;
        	
        	/*var avatarUrl=window.rootPath+'/a/'+'avatar/'+data.pictureAdress;
        	

        		jQuery("#avatar").prop("src",avatarUrl+'?t='+Math.random());*/
        	    
        		var purl=data.pictureAdress;
				if(purl==undefined||purl==""){
					purl="../img/nopicture.png";
				}else{
					purl=window.rootPath+'/'+purl;
				}
				$("#avatar").attr("src",purl);
    		
        		
        		var path ="";
        		if (data.infoState.title == '待认证') {
        			path="../img/authentication_in.png";
				} else if (data.infoState.title == '认证拒绝') {
					path="../img/authentication_notaccess.png";
				} else if (data.infoState.title == '认证通过') {
					path="../img/authentication_access.png";
				} else if (data.infoState.title == '初始化') {
					path="../img/authentication_init.png";
				} else if(data.infoState.title	==null){
					path ="";
				}
        		$("#infoState").attr('src',path); 
        	/*jQuery('#infoState').val(data.infoState.title);*/
        	
        	
    		if(data.infoState.title=="待认证"){
    			jQuery(".accessBtn").attr("disabled", false);
    			jQuery(".rejectBtn").attr("disabled", false);
    		}
    		else{
    			jQuery(".accessBtn").attr("disabled", true);
    			jQuery(".rejectBtn").attr("disabled", true);
    		}
    		
        	jQuery('#id').val(data.id);
        	jQuery('#createTime').val(data.createTime)
        	jQuery('#latitude').val(data.latitude)
        	jQuery('#longitude').val(data.longitude)
    		jQuery('#checkDate').val(data.checkDate);
        	jQuery('#submitDate').val(data.submitDate);
    		jQuery('#shopName').val(data.shopName);	
    		jQuery('#shopAdress').val(data.shopAdress);
    		
    		if(data.businesssellerBaseInfo.bussinessLevel!=null){
    			jQuery('#areaInfo').val(data.businesssellerBaseInfo.bussinessLevel.levelName);
        		jQuery('#areaInfoPhone').val(data.businesssellerBaseInfo.bussinessLevel.phoneNumber);
        		
        		if(data.businesssellerBaseInfo.bussinessLevel.manager!=null)
            		jQuery('#arreaManagementPerson').val(data.businesssellerBaseInfo.bussinessLevel.manager.name);
    		}
    		
    		if(data.managementPerson!=null){
    			jQuery('#managementPerson').val(data.managementPerson.name);	
    		}
    		
    		jQuery('#areaMeasure').val(data.areaMeasure);
    		jQuery('#signPerson').val(data.signPerson);
    		jQuery('#managementRange').val(data.managementRange);
    		jQuery('#cleaningPerson').val(data.cleaningPerson);
    		
			jQuery('#memo').val(data.memo);
			if(data.checkPerson){
				jQuery('#checkPerson').val(data.checkPerson.name);	
			}
    		jQuery('#checkModal').modal('show');
    		
    		createPoint(data);
        }
    });
    
    
    
    
    
    
})();